package cn.calm.swing.osgi.mysql.blance;

import java.util.Hashtable;
import java.util.List;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import cn.calm.swing.osgi.api.ProjectPersistenceService;
import cn.calm.swing.osgi.api.ProjectService;
import cn.calm.swing.osgi.api.WizardItemService;
import cn.calm.swing.osgi.api.entity.Project;
import cn.calm.swing.osgi.mysql.blance.service.MySqlBlanceProjectService;
import cn.calm.swing.osgi.mysql.blance.service.MySqlWizardItemService;
import cn.calm.swing.osgi.mysql.blance.ui.MySqlBlanceProjectDialog;

public class Activator implements BundleActivator {
	private ServiceRegistration<WizardItemService> registerService;
	private	ServiceRegistration<MySqlBlanceProjectDialog> registerService2;

	@Override
	public void start(BundleContext context) throws Exception {
		Hashtable<String, String> para = new Hashtable<String, String>();
		para.put(WizardItemService.WIZARD_ITEM_TREE, "MySql");
		registerService = context.registerService(WizardItemService.class,
				new MySqlWizardItemService(context), para);
		MySqlBlanceProjectDialog dialog=new MySqlBlanceProjectDialog(context);
		registerService2 = context.registerService(MySqlBlanceProjectDialog.class, dialog, null);
		loadProject(context);
	}

	private void loadProject(BundleContext context) {
		try {
			ServiceReference<ProjectPersistenceService> serviceReference = context.getServiceReference(ProjectPersistenceService.class);
			ProjectPersistenceService service = context.getService(serviceReference);
			List<Project> listAllByProjectType = service
					.listAllByProjectType(MySqlBlanceProjectDialog.MYSQL_PROJECT_TYPE);
			Hashtable<String, Object> dir = new Hashtable<String, Object>();
			dir.put(ProjectService.PROJECT_TYPE,
					MySqlBlanceProjectDialog.MYSQL_PROJECT_TYPE);
			MySqlBlanceProjectService service1;
			ServiceRegistration<ProjectService> registerService2;
			for (Project project : listAllByProjectType) {
				dir.put(ProjectService.PROJECT_ID, project.getId());
				service1 = new MySqlBlanceProjectService(context);
				service1.setProject(project);
				registerService2 = context.registerService(ProjectService.class, service1, dir);
				ProjectService.projectServiceRegistration.put(project.getId(), registerService2);
			}
			context.ungetService(serviceReference);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void stop(BundleContext context) throws Exception {
		if (registerService != null) {
			registerService.unregister();
		}
		if (registerService2 != null) {
			registerService2.unregister();
		}
	}
}
